const fs = require('fs')
const pinyins = require('./pinyins.json')
const mark = require('./mark.json')
const pkg = require('./package.json')

let dic = {};

let unMark = s => {
    let f = mark[s];
    return f ? f : s;
}

for(let k in pinyins) {
    let py = pinyins[k];
    // k = '\\u' + k.charCodeAt(0).toString(16).toUpperCase();
    let arr = py.split(',');
    if(arr.length == 1) {
        let z = unMark(arr[0][0]);
        if(!dic[z]) {
            dic[z] = {}
        }
        dic[z][k] = 1;
    } else {
        arr.map(x => {
            let z = unMark(x[0]);
            if(!dic[z]) {
                dic[z] = {}
            }
            dic[z][k] = 1;
        })
    }
}

let data = [];
let keys = Object.keys(dic).sort();
for(let i = 0; i < keys.length; i++) {
    let k = keys[i];
    data.push(k + ':"' + Object.keys(dic[k]).join('') + '",')
}

let addJs = `
/*处理开始*/
var dic = {};
for(var k in data) {
    data[k].split('').map(function(c) {
        if(!dic[c]) {
            dic[c] = [];
        }
        dic[c].push(k);
    });
}

var getResults = function(arr)
{
    var results = [];
    var result = [];
    var doExchange = function (arr, depth) {
        for (var i = 0; i < arr[depth].length; i++) {
            result[depth] = arr[depth][i]
            if (depth != arr.length - 1) {
                doExchange(arr, depth + 1)
            } else {
                results.push(result.join(''))
            }
        }
    }
    doExchange(arr, 0);
    return results;
}

var PYSZM = {
    get: function(text) {
        if(!text) return [];
        text = text.replace(/[\\r\\n\\t ]+/gi, '');
        var szm = [];
        text.split('').map(function(c,i) {
            var x = dic[c];
            if(!x) {
                x = [c];
            }
            szm.push(x);
        });
        return getResults(szm);
    }
}

// 自动导出AMD模块
if("object" == typeof module && "object" == typeof module.exports) {
    module.exports = PYSZM
}
// 挂载到window对象
if("object" == typeof window) {
    window.PYSZM = PYSZM
}
/*处理结束*/
`;
let jsCont = `
/*
拼音首字母工具包
制作：${pkg.author} 
版本：${pkg.version} 
许可：${pkg.license} 
构建时间：${new Date().toLocaleString()}
*/\r\n(function(){var data={\r\n${data.join('\r\n')}\r\n};\r\n${addJs}\r\n})();`
fs.writeFileSync('./pyszm.js', jsCont, 'utf-8');

console.log('mkdic finish.')